export default {
	data() {
		return {
			listStyle: '',
			loadingType: 'loading', //加载更多状态
			orderType: '',
			priceOrder: 'desc', //1 价格从低到高 2价格从高到低
			categoryList: [], //排序类型
			goodsList: [],
			order: '',
			sort: 'desc',
			showCategory: false,
			showScreen: false,
			keyword: '',
			categoryId: 0,
			minPrice: '',
			maxPrice: '',
			isFreeShipping: false, //是否免邮
			isIphoneX: false,
			coupon: 0,
			emptyShow:false,
			isList: true,  //列表样式
			
			cartList: [],
			goodsSkuDetail: {},
			cartFlag: false,
			token: '',
			cart_show: false,
			isShowPoint: false,
			cartBottom: '0',
			address: ''
		}
	},
	computed: {
		cartPrice() {
			return this.$store.state.cartPrice;
		},
		cartNumber() {
			if (this.$store.state.cartNumber == 0) {
				this.cart_show = false
			} else {
				this.cart_show = true
			}
			return this.$store.state.cartNumber;
		},
		cartIds() {
			return this.$store.state.cartIds;
		},
	},
	onLoad(options) {
		this.order = options.order || '';
		this.sort = options.sort || 'desc';
		this.orderType = this.order;
		
		this.categoryId = options.category_id || 0;
		this.keyword = options.keyword || '';
		this.loadCategoryList(this.categoryId);
		this.isIphoneX = this.$util.uniappIsIPhoneX();
		this.coupon = options.coupon || 0;
		
		if (this.$util.uniappIsIPhone11()) {
			this.cartBottom = '30px';
		}
	},
	onShow() {
		// 刷新多语言
		this.$langConfig.refresh();
		this.token = uni.getStorageSync('token') ? uni.getStorageSync('token') : '';
	},
	methods: {
		// 结算
		pay() {
			uni.setStorage({
				key: 'orderCreateData',
				data: {
					cart_ids: this.cartIds
				},
				success: () => {
					this.$util.redirectTo('/pages/order/payment/payment');
				}
			});
		},
		closePoint() {
			this.isShowPoint = false;
		},
		// 获取地址信息
		getAddress() {
			this.$api.sendRequest({
				url: '/api/community/getMemberCommunity',
				data: {
					token: this.token
				},
				success: res => {
					if (res.code >= 0) {
						this.isShowPoint = false;
						this.address = res.data.full_address;
						this.latitude = res.data.latitude;
						this.longitude = res.data.longitude;
						this.SelectCart()
					} else {
						this.isShowPoint = true;
						this.cart_show = false
					}
				},
				fail: res => {
					this.$util.showToast({
						title: res.message
					})
				}
			})
		},
		// 购物车处理
		SelectCart() {
			if (this.$store.state.cartNumber != 0) {
				this.cart_show = true
			}
		},
		
		
		getGoodsList(mescroll) {
			this.$api.sendRequest({
				url: '/api/goodssku/page',
				data: {
					page: mescroll.num,
					page_size: mescroll.size,
					keyword: this.keyword,
					category_id: this.categoryId,
					min_price: this.minPrice,
					max_price: this.maxPrice,
					is_free_shipping: (this.isFreeShipping ? 1 : 0),
					order: this.order,
					sort: this.sort,
					coupon: this.coupon
				},
				success: res => {
					let newArr = []
					let msg = res.message;
					if (res.code == 0 && res.data) {
						if(res.data.page_count == 0){
							this.emptyShow = true
						}
						newArr = res.data.list;
					} else {
						this.$util.showToast({
							title: msg
						})
					}
					mescroll.endSuccess(newArr.length);
					//设置列表数据
					if (mescroll.num == 1) this.goodsList = []; //如果是第一页需手动制空列表
					this.goodsList = this.goodsList.concat(newArr); //追加新数据
					this.getCartData();
					if (this.$refs.loadingCover) this.$refs.loadingCover.hide();
				},
				fail: res => {
					//联网失败的回调
					mescroll.endErr();
					if (this.$refs.loadingCover) this.$refs.loadingCover.hide();
				}
			});
		},
		getCartData() {
			this.$api.sendRequest({
				url: '/api/cart/lists',
				success: res => {
					if (res.code >= 0) {
						this.cartList = res.data;
		
						for (let goods_index in this.goodsList) {
							let goods_item = this.goodsList[goods_index],
								sku_id = goods_item.sku_id,
								num = 0,
								cart_id = '';
		
							for (let cart_index in this.cartList) {
								let cart_item = this.cartList[cart_index];
								if (sku_id == cart_item.sku_id) {
									num += cart_item.num;
									cart_id = cart_item.cart_id;
								}
							}
							goods_item.num = num;
							goods_item.cart_id = cart_id;
		
							if (typeof goods_item.num === 'undefined' || goods_item.num === null) {
								goods_item.num = 0;
							}
						}
						this.$forceUpdate();
					}
				}
			});
		},
		changeListStyle() {
			this.isList = !this.isList
		},
		//加载分类
		loadCategoryList(fid, sid) {
			this.$api.sendRequest({
				url: '/api/goodscategory/tree',
				data: {},
				success: res => {
					if (res.data != null) this.categoryList = res.data;
				}
			});
		},
		//筛选点击
		sortTabClick(tag) {
			if (tag == 'sale_num') {
				this.order = 'sale_num';
				this.sort = 'desc';
			} else if (tag == 'discount_price') {
				this.order = 'discount_price';
				this.sort = 'desc';
			} else if (tag == 'screen') {
				//筛选
				this.showScreen = true;
				return;
			} else {
				this.order = '';
				this.sort = '';
			}

			if (this.orderType === tag && tag !== 'discount_price') return;

			this.orderType = tag;
			if (tag === 'discount_price') {
				this.priceOrder = this.priceOrder === 'asc' ? 'desc' : 'asc';
				this.sort = this.priceOrder;
			} else {
				this.priceOrder = '';
			}
			this.emptyShow = false;
			this.goodsList = [];
			this.$refs.mescroll.refresh();
		},
		//商品详情
		toDetail(item) {
			this.$util.redirectTo('/pages/goods/detail/detail', {
				sku_id: item.sku_id
			});
		},
		search() {
			this.emptyShow = false;
			this.goodsList = [];
			this.$refs.mescroll.refresh();
		},
		selectedCategory(categoryId) {
			this.categoryId = categoryId;
		},
		screenData() {
			if (this.minPrice != '' || this.maxPrice != '') {
				if (!Number(this.minPrice) && this.minPrice) {
					this.$util.showToast({
						title: '请输入最低价'
					});
					return;
				}
				if (!Number(this.maxPrice)  && this.maxPrice) {
					this.$util.showToast({
						title: '最输入最高价'
					});
					return;
				}
				if (Number(this.minPrice) < 0 || Number(this.maxPrice) < 0) {
					this.$util.showToast({
						title: '筛选价格不能小于0'
					});
					return;
				}
				if (this.minPrice != '' && Number(this.minPrice) > Number(this.maxPrice) && this.maxPrice) {

					this.$util.showToast({
						title: '最低价不能大于最高价'
					});
					return;
				}
				if (this.maxPrice != '' && Number(this.maxPrice) < Number(this.minPrice)) {
					this.$util.showToast({
						title: '最高价不能小于最低价'
					});
					return;
				}
			}
			this.emptyShow = false;
			this.goodsList = [];
			this.$refs.mescroll.refresh();
			this.showScreen = false;
		},
		//重置数据
		resetData(){
			this.categoryId = 0
			this.minPrice= ''
			this.maxPrice= ''
			this.isFreeShipping= false
		},
		goodsImg(imgStr){
			let imgs = imgStr.split(',');
			return imgs[0] ? this.$util.img(imgs[0], { size: 'mid' }) : this.$util.getDefaultImage().default_goods_img;
		},
		imgError(index){
			this.goodsList[index].goods_image = this.$util.getDefaultImage().default_goods_img;
		},
		showPrice(data){
			let price = data.discount_price; 
			if (data.member_price && parseFloat(data.member_price) < parseFloat(price)) price = data.member_price;
			return price;
		},
		goodsTag(data) {
			switch (data.recommend_way) {
				case 1:
					return '好货上新';
					break;
				case 2:
					return '精品优选';
					break;
				case 3:
					return '每日推荐';
					break;
				default:
					return '';
			}
		},
		
		
		//获取购物车数量
		getCartCount() {
			this.$store.dispatch('getCartNumber').then((e) => {
				this.cartCount = e;
			})
		},
		// 刷新商品sku详情数据
		refreshGoodsSkuDetail(goodsSkuDetail) {
			Object.assign(this.goodsSkuDetail, goodsSkuDetail);
		},
		async getGoodsSkuDetail(skuId) {
			if (!uni.getStorageSync('token')) {
				this.$refs.login.open(this.currentRoute);
				return;
			}
		
			let res = await this.$api.sendRequest({
				url: '/api/goodssku/getInfoForCategory',
				async: false,
				data: {
					sku_id: skuId,
				}
			});
		
			let data = res.data;
			if (data) {
				this.goodsSkuDetail = data;
		
				if (this.skuId == 0) this.skuId = this.goodsSkuDetail.sku_id;
		
				this.goodsSkuDetail.unit = this.goodsSkuDetail.unit || "件";
		
				this.goodsSkuDetail.show_price = this.goodsSkuDetail.discount_price;
		
				// 当前商品SKU规格
				if (this.goodsSkuDetail.sku_spec_format) this.goodsSkuDetail.sku_spec_format = JSON.parse(this.goodsSkuDetail.sku_spec_format);
		
				// 商品SKU格式
				if (this.goodsSkuDetail.goods_spec_format) this.goodsSkuDetail.goods_spec_format = JSON.parse(this.goodsSkuDetail
					.goods_spec_format);
		
				this.$refs.goodSkuNew.show("join_cart", this.goodsSkuDetail, () => {
					this.getCartCount();
				});
			} else {
				this.$util.redirectTo('/pages/index/index/index', {}, 'reLaunch');
			}
		},
		// 变更购物车数量
		cartNumChange(type, goods) {
			if (!uni.getStorageSync('token')) {
				this.$refs.login.open('/pages/goods/category/category');
				return;
			}
		
			let cartData = {
					num: 1,
					cart_id: goods.cart_id,
					sku_id: goods.sku_id
				},
				cartUrl = "", //类型 add--新增商品  edit--修改商品数量  delete--删除商品
				actionType,
				maxBuy = goods.max_buy,
				stock = maxBuy > 0 ? (maxBuy - goods.purchased_num) : goods.stock;
		
			var minBuy = 1;
			if (goods.min_buy > 1) minBuy = goods.min_buy;
			cartData.num = minBuy; // 最少购买量
		
			goods.unit = goods.unit || "件";
		
			if (type == 'add') {
		
				// 检测是否第一次加入购物车
				if (goods.cart_id) {
					actionType = "edit";
					cartUrl = '/api/cart/edit';
				} else {
					actionType = "add";
					cartUrl = '/api/cart/add';
				}
				if (stock == 0) {
					this.$util.showToast({
						title: '库存不足'
					});
					return;
				} else if (goods.cart_id && goods.num < stock) {
					cartData.num = ++goods.num;
				} else {
					if (maxBuy > 0 && (goods.purchased_num + goods.num) >= maxBuy) {
						this.$util.showToast({
							title: '该商品每人限购' + maxBuy + goods.unit + '，您已购买了' + goods.purchased_num + goods.unit
						});
						return;
					}
		
					if (maxBuy > 0 && goods.num > 0 && goods.num + cartData.num > maxBuy) {
						var diff = maxBuy - goods.num;
						if (diff > 0) {
							this.$util.showToast({
								title: '该商品每人限购' +
									maxBuy +
									goods.unit +
									'，购物车已加入了' +
									goods.num +
									goods.unit +
									'，还能购买' +
									diff +
									goods.unit
							});
						} else {
							this.$util.showToast({
								title: '该商品每人限购' + maxBuy + goods.unit
							});
						}
						return;
					}
				}
		
			} else if (type == 'minus') {
				cartData.num = goods.num - 1 ? goods.num - 1 : 0;
				cartUrl = cartData.num > 0 ? '/api/cart/edit' : '/api/cart/delete';
				actionType = cartData.num > 0 ? 'edit' : 'delete';
			}
		
			if (this.cartFlag) return false;
			this.cartFlag = true;
		
			this.shopDataChange(cartData);
		
			this.$api.sendRequest({
				url: cartUrl,
				data: cartData,
				success: res => {
					if (res.code >= 0) {
						if (res.data > 0) {
							this.$store.dispatch('getCartNumber');
							this.$store.dispatch('getCartPrice');
							this.$store.dispatch('getCartIds');
							if (actionType == "edit") {
								this.cartFlag = false;
								return false;
							}
							cartData.cart_id = actionType == "add" ? res.data : '';
							if (actionType == 'add') {
								this.$util.showToast({
									title: '加入购物车成功'
								});
							}
						} else {
							cartData.num = goods.num;
							this.$util.showToast({
								title: res.message
							});
						}
						this.shopDataChange(cartData);
					}
		
					this.cartFlag = false;
				}
			});
		
		},
		shopDataChange(data) {
			for (var i = 0; i < this.goodsList.length; i++) {
				var item = this.goodsList[i];
				if (data.sku_id == item.sku_id) {
					item.num = data.num;
					item.cart_id = data.cart_id;
				}
			}
			this.$forceUpdate();
		},
	}

}
